import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useCounterStore } from '@/stores/counter'

const read = axios.create({
    baseURL: 'http://localhost:8676',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8', // 关键：指定 JSON 格式
    },
})

//请求拦截器
read.interceptors.request.use(
    config => {
        const store = useCounterStore()
        config.headers["Authorization"] = "Bearer " + store.usercount.token;
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

//响应拦截器
read.interceptors.response.use(
    res => {
        return res
    },
    error => {
        if (error.response?.status === 401) {
            ElMessage.error('登录已过期，请重新登录')
            localStorage.removeItem('token')
            setTimeout(() => {
                window.location.href = '/'
            }, 1000)
        }
        return Promise.reject(error)
    }
)

export default read